package com.zjd.controller.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjd.domain.User;
import com.zjd.service.UserService;
import com.zjd.service.impl.UserServiceImpl;
import com.zjd.utils.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/UserServlet")
public class UserServlet extends BaseServlet {

    private UserService service = new UserServiceImpl();

    public void login() throws IOException, ServletException {
        ServletInputStream userStream = request.getInputStream();
        User logoinUser = new ObjectMapper().readValue(userStream, User.class);
        User flagUser = service.login(logoinUser);
        request.getSession().setAttribute("flagUser",flagUser);
        writeJson(response,flagUser);
    }

    public void saveUser() throws IOException {
        ServletInputStream userStream = request.getInputStream();
        User reUser = new ObjectMapper().readValue(userStream, User.class);
        service.saveUser(reUser);
        response.getWriter().write("ok");
    }

    public void checkUserLogin() throws ServletException, IOException {

        User flagUser = (User) request.getSession().getAttribute("flagUser");

        writeJson(response,flagUser);
    }

    public void updateUser() throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        User user = new ObjectMapper().readValue(inputStream, User.class);
        service.updateUser(user);
        response.getWriter().write("ok");
    }
}